package com.css.ids.server.service.dao;

import java.util.ArrayList;
import java.util.List;

import com.css.apps.base.common.Constants;
import com.css.apps.base.func.model.SFunc;
import com.css.apps.base.menu.model.SMenu;
import com.css.apps.base.role.model.SRole;
import com.css.core.model.tree.Tree;
import com.css.core.model.tree.TreeCache;
import com.css.core.model.tree.TreeNode;
import com.css.db.query.QueryCache;
import com.css.util.StringHelper;
import com.css.webbase.menu.MenuItem;

public class IdsMenuDao {

	/**
	 * 根据菜单ID获取菜单信息
	 */
	public static SMenu getMenu(String menuId) {
		return QueryCache.get(SMenu.class, menuId);
	}

	public static List<MenuItem> listMenusByRole(SRole role, String sysId) {
		List<MenuItem> items = new ArrayList<>();
		Tree tree = new TreeCache(SMenu.class);
		List<TreeNode> roots = tree.getRoot();
		if (roots != null && roots.size() != 0) {
			for (TreeNode root : tree.getRoot()) {
				int level = 1;
				MenuItem mi = transpass(root, level, role, sysId);
				if (mi != null) {
					items.add(mi);
				}
			}
		}
		return items;
	}

	private static MenuItem transpass(TreeNode node, int level, SRole role, String sysId) {
		// 获取所有子节点
		List<TreeNode> sMenuNodes = node.getChildren();
		String curMenuId = node.getNodeId();
		MenuItem menuItem = new MenuItem();
		SMenu menu = QueryCache.get(SMenu.class, curMenuId);
		if (menu != null && Constants.YES.equals(menu.getOpenFlag()) && sysId.equals(menu.getSysId())) {
			String funcId = menu.getFuncId();
			String url = menu.getUrl();
			if (!(StringHelper.isEmptyByTrim(funcId) && StringHelper.isEmptyByTrim(url)) && !hasPrivilege(role, funcId)) {
				return null;
			}
			menuItem.setId(menu.getMenuId());
			menuItem.setIcon(menu.getIcon());
			menuItem.setLevel(level);
			menuItem.setName(menu.getMenuName());
			menuItem.setOpenIcon(menu.getIcon());
			menuItem.setPath(url);
			menuItem.setFuncode(menu.getFuncId());
			menuItem.setParentId(menu.getParentId());
			menuItem.setVisible(true);
			if (sMenuNodes.isEmpty()) {
				menuItem.setIsLast(true);
			} else {
				menuItem.setIsLast(false);
			}
		} else {
			return null;
		}

		if (sMenuNodes != null && !sMenuNodes.isEmpty()) {
			for (TreeNode node1 : sMenuNodes) {
				MenuItem mi = transpass(node1, level + 1, role, sysId);
				if (mi != null) {
					menuItem.getMenus().add(mi);
				}
			}
			String funcId = menu.getFuncId();
			String url = menu.getUrl();

			if (StringHelper.isEmptyByTrim(funcId) && StringHelper.isEmptyByTrim(url)
					&& menuItem.getMenus().isEmpty()) {
				return null;
			}
		}
		return menuItem;
	}

	/**
	 * 判断角色是否有funcCode
	 */
	@SuppressWarnings("unchecked")
	private static boolean hasPrivilege(SRole role, String funcCode) {
		List<SFunc> funcs = role.getRoleFuncList().getList();
		for (SFunc func : funcs) {
			if (func.getFuncCode().equals(funcCode)) {
				return true;
			}
		}
		return false;
	}

}
